package test;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Receive {
    public static void main(String[] args) throws Exception {
        //1、基于UDP协议创建Socket对象
        DatagramSocket ds = new DatagramSocket(9999);
        //2、创建数据包对象
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf,buf.length);
        //3、接受数据包  receive阻塞式的方法
        ds.receive(dp);

        //4、解析数据包的数据
        //从数据包中获取数据
        byte[] data = dp.getData();
        //从数据包中获取InetAddress对象
        InetAddress inetAddress = dp.getAddress();
        //从数据包中获取端口号
        int port = dp.getPort();
        //获取数据包的数据字节数长度
        int length = dp.getLength();


        String str = new String(data,0,length);
        System.out.println("ip:"+inetAddress.getHostAddress());
        System.out.println("port:"+port);
        System.out.println("data:"+str);

        //5、释放资源
        ds.close();
    }
}